package com.stickerview.view;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.qozix.tileview.R;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by felix on 2017/12/12 下午4:26.
 */

public class JTDView extends ViewGroup implements View.OnClickListener {


    private View mContentView;
    private TextView textView;
    private Context mContext;
    private JTDView.Callback mCallback;


    private float mScale = 1f;

    private int state ;



    private AssetManager assetManager ;
    private Paint PAINT;

    private Matrix mMatrix = new Matrix();

    private RectF mFrame = new RectF();

    private Rect mTempFrame = new Rect();
    private ViewFlipper viewFlipper;

    private static final int ANCHOR_SIZE = 48;

    private static final int ANCHOR_SIZE_HALF = ANCHOR_SIZE >> 1;

    private static final float STROKE_WIDTH = 3f;

    {
        PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
        PAINT.setColor(Color.TRANSPARENT);
        PAINT.setStyle(Paint.Style.STROKE);
        PAINT.setStrokeWidth(STROKE_WIDTH);
    }

    private int fontSize = 13;
    public JTDView(Context context ) {
        this(context, null, 0 );
    }
    public JTDView(Context context, AttributeSet attrs ) {
        this(context, attrs, 0);
    }
    public JTDView(Context context, AttributeSet attrs, int defStyleAttr ) {
        super(context, attrs, defStyleAttr);
        this.mContext = context ;
        assetManager = mContext.getAssets();
    }
    public void registerCallback(JTDView.Callback callback) {
        mCallback = callback;
    }

    public void unregisterCallback(JTDView.Callback callback) {
        mCallback = null;
    }

    public void setData(int state,String num) {
        this.state = state;
        setBackgroundColor(Color.TRANSPARENT);
        assetManager=getContext().getAssets();

        if(state==13){
            viewFlipper = new ViewFlipper(mContext);
            viewFlipper.setBackground(getResources().getDrawable(R.drawable.warning_bg));
            viewFlipper.setFlipInterval(3000);
            AnimationSet inAnim = (AnimationSet) AnimationUtils.loadAnimation(
                    mContext, R.anim.slide_in_bottom);
            AnimationSet outAnim = (AnimationSet) AnimationUtils.loadAnimation(
                    mContext, R.anim.slide_out_top);
            viewFlipper.setInAnimation(inAnim);
            viewFlipper.setOutAnimation(outAnim);
            num = num.trim();

            if(num.equals("")){
                mContentView = onCreateContentView(mContext,state);
                addView(mContentView, getContentLayoutParams());
            }else{
                List<String> arr = new ArrayList<String>();
                if(num.length()>5){
                    char a[]=num.toCharArray();
                    String temp = "";
                    for(int i = 0 ; i < a.length;i++){
                        if(i%5==0){
                            if(temp!=""){
                                arr.add(temp);
                            }
                            temp = "";
                        }
                        temp+=a[i];

                    }
                    if(temp!=""){
                        arr.add(temp);
                    }
                }else{
                    arr.add(num);
                }

                for(int i = 0 ; i<arr.size();i++){
                    textView = new TextView(mContext);
                    textView.setText(arr.get(i));
                    textView.setEms(1);
                    textView.setGravity(Gravity.LEFT);
                    textView.setTextColor(getResources().getColor(R.color.red));
                    textView.setTextSize(16);
                    if(i==0){
                        viewFlipper.addView(textView, getAnchorLayoutParams());
                    }else{
                        viewFlipper.addView(textView, getContentLayoutParams());
                    }

                }

                mContentView = viewFlipper ;
                addView(mContentView, new LayoutParams(25,90));

                if(num.length()>5) {
                    viewFlipper.startFlipping();
                }
            }
        }else{
            mContentView = onCreateContentView(mContext,state);
            addView(mContentView, getContentLayoutParams());
        }
        mContentView.setOnClickListener(this);


        if(state==4) {
            textView = new TextView(mContext);
            textView.setText(num);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(getResources().getColor(R.color.white));
            textView.setTextSize(fontSize+2*mScale);
            addView(textView, getAnchorLayoutParams());
        }

    }
    public  View onCreateContentView(Context context,int state){
        String path = null;
        if(state==1){
            path = "jtd/left.png";
        }else if(state==2){
            path = "jtd/right.png";
        }else if(state==3){
            path = "jtd/stop.png";
        }else if(state==4){
            path = "jtd/o.png";
        }else if(state==5){
            path = "jtd/left_left.png";
        }else if(state==6){
            path = "jtd/left_right.png";
        }else if(state==7){
            path = "jtd/right_left.png";
        }else if(state==8){
            path = "jtd/right_right.png";
        }else if(state==9){
            path = "jtd/red_big.png";
        }else if(state==10){
            path = "jtd/yellow_big.png";
        }else if(state==11){
            path = "jtd/green_big.png";
        }else if(state==12){
            path = "jtd/default_big.png";
        }else if(state==13){
            path = "jtd/qbb.png";
        }
        ImageView imageView = new ImageView(context);
        try {
            InputStream in=assetManager.open(path);
            Bitmap bmp=BitmapFactory.decodeStream(in);
            imageView.setImageBitmap(bmp);
            return  imageView ;
        }catch (Exception e){
            imageView.setBackgroundResource(R.drawable.default_bg);
            Log.e("jtd_err",e.getMessage());
        }
        return imageView;
    }

    public void setLastScale(){
        drowFrame(getScale());
    }
    public void setScale(float scale) {
        this.mScale = scale;
        drowFrame(scale);
    }
    public void drowFrame(float mScale){
        mContentView.setScaleX(mScale);
        mContentView.setScaleY(mScale);
        int pivotX = (getLeft() + getRight()) >> 1;
        int pivotY = (getTop() + getBottom()) >> 1;

        mFrame.set(pivotX, pivotY, pivotX, pivotY);
        mFrame.inset(-(mContentView.getMeasuredWidth() >> 1), -(mContentView.getMeasuredHeight() >> 1));

        mMatrix.setScale(mScale, mScale, mFrame.centerX(), mFrame.centerY());
        mMatrix.mapRect(mFrame);
        mFrame.round(mTempFrame);



        if(state==4) {
            textView.setTextSize(fontSize+2*mScale);
        }
        layout(mTempFrame.left, mTempFrame.top, mTempFrame.right, mTempFrame.bottom);
    }

    public void addScale(float scale) {
        setScale(getScale() * scale);
    }

    public float getScale() {
        return this.mScale;
    }

    private LayoutParams getContentLayoutParams() {
        return new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );
    }

    private LayoutParams getAnchorLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    public void draw(Canvas canvas) {
            canvas.drawRect(ANCHOR_SIZE_HALF, ANCHOR_SIZE_HALF,
                    getWidth() - ANCHOR_SIZE_HALF,
                    getHeight() - ANCHOR_SIZE_HALF, PAINT);
        super.draw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                child.measure(widthMeasureSpec, heightMeasureSpec);

                maxWidth = Math.round(Math.max(maxWidth, child.getMeasuredWidth() * child.getScaleX()));
                maxHeight = Math.round(Math.max(maxHeight, child.getMeasuredHeight() * child.getScaleY()));

                childState = combineMeasuredStates(childState, child.getMeasuredState());
            }
        }

        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        mFrame.set(left, top, right, bottom);

        int count = getChildCount();
        if (count == 0) {
            return;
        }

        int centerX = (right - left) >> 1, centerY = (bottom - top) >> 1;
        int hw = mContentView.getMeasuredWidth() >> 1;
        int hh = mContentView.getMeasuredHeight() >> 1;
        mContentView.layout(centerX - hw, centerY - hh, centerX + hw, centerY + hh);
        if(state==4) {
            textView.layout(centerX - hw+2, centerY - hh+2, centerX + hw+2, centerY + hh+2);
        }
    }

    @Override
    public void onClick(View view) {
        if(view==mContentView){
            mCallback.onSelect(this);
        }
    }

    public interface Callback {
        void onSelect(View v);
    }
}
